﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace HM
{
    public class Gettrackings
    {
        //<summary>
        ///发送Get请求
        ///</summary>
        ///<param name = "ur1" > 地址 </ param >
        ///< param name="dic">请求参数定义</param><returns></returns>
        public static string Get(string url, Dictionary<string, string> pairs)
        {
            string result = string.Empty;
            string error = string.Empty;
            try
            {
                StringBuilder sb = new StringBuilder();
                foreach (string key in pairs.Keys)
                    sb.Append(key).Append("=").Append(pairs[key]).Append("&");
                if (pairs.Count > 0)
                    url = url + "?" + sb.ToString().Trim('&');

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "application/json"; //表单数据(键值对)
                request.Timeout = 20000;  //超时时间
                request.Method = "GET";  //请求方式
                //request.KeepAlive = true; //解决GetResponse操作超时问题
                //request.Headers.Add("Authorization", "token"); //如果接口需要鉴权, 把"token"换成自己需要的
                request.Headers.Add("Tracking-Api-Key", "h73buxu6-989y-uakh-yitu-sa6m9hkmaveb");

                //通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //获取响应内容，返回的数据格式: {"status":"success","msg":"成功","data":{"info": "example"}}
                string postContent = new StreamReader(response.GetResponseStream()).ReadToEnd();

                //结果解析,异常情况判断
                JObject json = JObject.Parse(postContent);
                //var gList = json["data"];
                //if (json["status"] == null || gList == null || json["msg"] == null)
                //    error = "接口错误";
                //else if (json["status"].ToString() != "success")
                //    error = string.Format("接口查询结果返回错误,{0}", json["msg"]);
                //else if (gList.ToString() != string.Empty)
                //    result = gList["info"].ToString();
                //else { }
                result = json.ToString();
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            //if (error != string.Empty)
            //    MessageBox.Show(error);

            return result;

        }
    }
}
